package com.itjeffrey.autocode.security;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 生成令牌，验证等等一些操作
 *
 * @From: Jeffrey
 * @Date: 2020/12/04
 */
@Slf4j
@Data
@Component
public class JwtTokenUtil {

    @Value("${jwt.secret}")
    private String secret;

    // 过期时间 毫秒
    @Value("${jwt.expiration}")
    private String expiration;

    //刷新时间 毫秒
    @Value("${jwt.refreshExpiration}")
    private String refreshExpiration;

    @Value("${jwt.header}")
    private String header;

    /**
     * 从数据声明生成访问令牌
     *
     * @param claims 数据声明
     * @return 令牌
     */
    private String generateToken(Map<String, Object> claims) {
        Date expirationDate = new Date(System.currentTimeMillis() + Long.valueOf(expiration));
        return Jwts.builder().setClaims(claims).setExpiration(expirationDate).signWith(SignatureAlgorithm.HS512,
                secret).compact();
    }

    /**
     * 从数据声明中生成刷新令牌
     *
     * @param claims
     * @return
     */
    private String generateRefreshToken(Map<String, Object> claims) {
        Date expirationDate = new Date(System.currentTimeMillis() + Long.valueOf(refreshExpiration));
        return Jwts.builder().setClaims(claims).setExpiration(expirationDate).signWith(SignatureAlgorithm.HS512,
                secret).compact();
    }

    /**
     * 从令牌中获取数据声明
     *
     * @param token 令牌
     * @return 数据声明
     */
    private Map<Object, Object> getClaimsFromToken(String token) {
        HashMap<Object, Object> map = new HashMap<>();
        Claims claims;
        try {
            claims = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
        } catch (ExpiredJwtException e) {
            map.put("claims", null);
            map.put("isExpire", true);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        map.put("claims", claims);
        map.put("isExpire", false);
        return map;
    }

    /**
     * 生成令牌
     *
     * @param userDetails 用户
     * @return 令牌
     */
    public Map<String, String> generateToken(UserDetails userDetails) {
        Map<String, Object> claims = new HashMap<>(2);
        claims.put(Claims.SUBJECT, userDetails.getUsername());
        claims.put(Claims.ISSUED_AT, new Date());
        Map<String, String> map = new HashMap<>();
        map.put("token", generateToken(claims));
        map.put("refreshToken", generateRefreshToken(claims));
        return map;
    }

    /**
     * 从令牌中获取用户名
     *
     * @param token 令牌
     * @return 用户名
     */
    public String getUsernameFromToken(String token) {
        String username = null;
        try {
            Map<Object, Object> map = getClaimsFromToken(token);
            if (map == null) {
                return "-1";
            }
            if ((boolean) map.get("isExpire")) {
                return "-2";
            }
            Claims claims = (Claims) map.get("claims");
            username = claims.getSubject();
        } catch (Exception e) {
            username = null;
        }
        return username;
    }

    /**
     * 判断令牌是否过期
     *
     * @param token 令牌
     * @return 是否过期
     */
    public Boolean isTokenExpired(String token) {
        Date expiration = new Date();
        try {
            Map<Object, Object> map = getClaimsFromToken(token);
            if (map != null && !(boolean) map.get("isExpire")) {
                Claims claims = (Claims) map.get("claims");
                expiration = claims.getExpiration();
            }
            return expiration.before(new Date());
        } catch (Exception e) {
            return true;
        }
    }

    /**
     * 刷新令牌
     *
     * @param token 原令牌
     * @return 新令牌
     */
    public Map<String, String> refreshToken(String token) {
        Map<String, String> tokenMap = null;
        try {
            Map<Object, Object> map = getClaimsFromToken(token);
            //accessToken存在且已过期则刷新token
            if (map != null && (boolean) map.get("isExpire") && map.get("claims") == null) {
//                Claims claims = (Claims) map.get("claims");
//                claims.put(Claims.ISSUED_AT, new Date());
//                refreshedToken = generateToken(claims);
                tokenMap = generateToken(new JwtUserDetails(getUsernameFromToken(token), null, null));
            }
        } catch (Exception e) {
            tokenMap = null;
        }
        return tokenMap;
    }

    /**
     * 刷新访问token
     *
     * @param token
     * @return
     */
    public String refreshAccessToken(String token) {
        String accessToken = null;
        try {
            Map<Object, Object> claimsFromToken = getClaimsFromToken(token);
            accessToken = generateToken((Claims) claimsFromToken.get("claims"));
        } catch (Exception e) {
            accessToken = null;
        }
        return accessToken;
    }

    /**
     * 验证令牌
     *
     * @param token       令牌
     * @param userDetails 用户
     * @return 是否有效 true-token有效 false-token过期失效
     */
    public Boolean validateToken(String token, UserDetails userDetails) {
        JwtUserDetails user = (JwtUserDetails) userDetails;
        String username = getUsernameFromToken(token);
        return (username.equals(user.getUsername()) && !isTokenExpired(token));
    }

}